package cn.com.fuhuitong.main.mine.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.lifecycle.Observer
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.WX_APP_ID
import cn.com.fuhuitong.app.getImageUrl
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.ItemViewType
import cn.com.fuhuitong.main.base.ViewModeActivity
import cn.com.fuhuitong.main.mine.adapter.ShareListAdapter
import cn.com.fuhuitong.main.mine.entity.MineShareCenterEntity
import cn.com.fuhuitong.main.mine.vm.ShareViewModel
import cn.com.fuhuitong.utils.SpanUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.android.vlayout.layout.LinearLayoutHelper
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.android.synthetic.main.activity_mine_share.*
import java.io.BufferedInputStream
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLConnection


@Route(path = ARouteConstance.ACTIVITY_URL_MINE_SHARE)
class MineShareActivity : ViewModeActivity<ShareViewModel>() {

    private lateinit var shareListAdapter: ShareListAdapter

    override fun viewModel(): ShareViewModel = createViewModel()

    override val layoutResId: Int
        get() = R.layout.activity_mine_share

    override fun initView() {

        image_mine_share_back.setOnClickListener {
            this.finish()
        }

        this.initViewRecyclerAdapter(
            recycler_mine_share_list, arrayOf(ItemViewType.SHARE_LIST)
        )

        delegateAdapter.addAdapter(
            ShareListAdapter(this, LinearLayoutHelper())
                .apply { shareListAdapter = this }
        )

        text_mine_share_withdraw.setOnClickListener {
            ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_MINE_WITHDRAW)
                .withInt("actionType", 2)
                .navigation()
        }

        text_mine_share.setOnClickListener {
            viewModel.share()
        }

    }

    override fun initViewMode() {

        viewModel.mineShareCenterDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let {
                fillData(it)
            }
        })

        viewModel.mineShareDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)


            when (response.status) {
                HttpResponseStatus.Status.START -> showLoadingView()
                HttpResponseStatus.Status.FAILURE -> {
                    hideLoadingView()
                    toast(response.statusTip)
                }
            }
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            val shareEntity = response.response?.data
            if (shareEntity == null) {
                hideLoadingView()
                toast("分享参数为空")
                return@Observer
            }
            val image = shareEntity.image
            if (image.isNullOrEmpty()) {
                hideLoadingView()
                shareWeb(
                    context = this@MineShareActivity,
                    appId = WX_APP_ID,
                    webUrl = shareEntity.url,
                    title = shareEntity.title,
                    content = shareEntity.describe,
                    bitmap = null
                )
            } else {
                Thread {
                    val bitmap = try {
                        getBitmap(getImageUrl(image))
                    } catch (e: Exception) {
                        toast("分享图片下载失败！请检查网络是否连接！${e.message}")
                        null
                    }
                    runOnUiThread {
                        hideLoadingView()
                        shareWeb(
                            context = this@MineShareActivity,
                            appId = WX_APP_ID,
                            webUrl = shareEntity.url,
                            title = shareEntity.title,
                            content = shareEntity.describe,
                            bitmap = bitmap
                        )
                    }
                }.start()


//                    Thread {
//                        Glide.with(this@MineShareActivity).asBitmap().load(getImageUrl(image))
//                            .into(object : CustomTarget<Bitmap>() {
//                                override fun onResourceReady(
//                                    resource: Bitmap,
//                                    transition: Transition<in Bitmap>?
//                                ) {
//                                    runOnUiThread {
//                                        shareWeb(
//                                            context = this@MineShareActivity,
//                                            appId = WX_APP_ID,
//                                            webUrl = it.url,
//                                            title = it.title,
//                                            content = it.describe,
//                                            bitmap = resource
//                                        )
//                                    }
//                                }
//
//                                override fun onLoadFailed(errorDrawable: Drawable?) {
//                                    super.onLoadFailed(errorDrawable)
//                                    runOnUiThread {
//                                        shareWeb(
//                                            context = this@MineShareActivity,
//                                            appId = WX_APP_ID,
//                                            webUrl = it.url,
//                                            title = it.title,
//                                            content = it.describe,
//                                            bitmap = null
//                                        )
//                                    }
//                                }
//
//                                override fun onLoadCleared(placeholder: Drawable?) = Unit
//
//                            })
//                    }.start()

            }
        })
    }

    override fun initData() {
        viewModel.distributionCenter()
    }

    private fun getImage(urlPath: String): Bitmap? = try {
        val url = URL(urlPath)
        val code = url.openConnection().getHeaderField(0)
        if (code.indexOf("200") < 0) {
            throw Exception("图片文件不存在或路径错误${code}")
        }
        BitmapFactory.decodeStream(url.openStream())
    } catch (e: Exception) {
        throw Exception(e.message)
    }

    fun getBitmap(url: String): Bitmap? {
        var bm: Bitmap? = null
        try {
            val iconUrl = URL(url)
            val conn: URLConnection = iconUrl.openConnection()
            val http: HttpURLConnection = conn as HttpURLConnection
            val length: Int = http.getContentLength()
            conn.connect()
            // 获得图像的字符流
            val `is`: InputStream = conn.getInputStream()
            val bis = BufferedInputStream(`is`, length)
            bm = BitmapFactory.decodeStream(bis)
            bis.close()
            `is`.close() // 关闭流
        } catch (e: Exception) {
            throw Exception(e.message)
        }
        return bm
    }

    @SuppressLint("SetTextI18n")
    private fun fillData(centerEntity: MineShareCenterEntity) {
        text_mine_share_price.text = SpanUtils.setMoneyStyle(centerEntity.sum.toDouble())
        text_mine_share_level_health.text = centerEntity.one_level.toString()
        text_mine_share_level_home.text = centerEntity.two_level.toString()
        text_mine_share_level_flagship.text = centerEntity.three_level.toString()
        text_mine_share_count.text = "邀请记录（${centerEntity.count}）"
        if (centerEntity.list.isEmpty())
            return
        shareListAdapter.setAddDataNew(centerEntity.list)
    }


    /**
     * 分享网页类型至微信
     *
     * @param context 上下文
     * @param appId   微信的appId
     * @param webUrl  网页的url
     * @param title   网页标题
     * @param content 网页描述
     * @param bitmap  位图
     */
    fun shareWeb(
        context: Context?,
        appId: String?,
        webUrl: String?,
        title: String?,
        content: String?,
        bitmap: Bitmap?
    ) {
        // 通过appId得到IWXAPI这个对象
        val wxapi = WXAPIFactory.createWXAPI(context, appId)
        // 检查手机或者模拟器是否安装了微信
        if (!wxapi.isWXAppInstalled) {
            toast("手机未安装微信")
            return
        }

        // 初始化一个WXWebpageObject对象
        val webpageObject = WXWebpageObject()
        // 填写网页的url
        webpageObject.webpageUrl = webUrl

        // 用WXWebpageObject对象初始化一个WXMediaMessage对象
        val msg = WXMediaMessage(webpageObject)
        // 填写网页标题、描述、位图
        msg.title = title
        msg.description = content
        // 如果没有位图，可以传null，会显示默认的图片
        msg.setThumbImage(bitmap)

        // 构造一个Req
        val req = SendMessageToWX.Req()
        // transaction用于唯一标识一个请求（可自定义）
        req.transaction = System.currentTimeMillis().toString()
        // 上文的WXMediaMessage对象
        req.message = msg
        // SendMessageToWX.Req.WXSceneSession是分享到好友会话
        // SendMessageToWX.Req.WXSceneTimeline是分享到朋友圈
        req.scene = SendMessageToWX.Req.WXSceneSession

        // 向微信发送请求
        wxapi.sendReq(req)
    }

}